package com.qdlc.p2p.manage.action.additional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qd.p2p.sina.pay.enums.CardType;
import com.qdlc.p2p.biz.service.AdditionalUserCardService;
import com.qdlc.p2p.biz.service.additional.CardRuleService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.UserCardStatus;
import com.qdlc.p2p.common.enums.EnumCardType;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.common.util.excel.ExcelUtils;
import com.qdlc.p2p.common.util.excel.JsGridReportBase;
import com.qdlc.p2p.common.util.excel.TableData;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.CardRule;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AdditionalUserCardModel;
import com.qdlc.p2p.dal.model.CardRuleModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 管理用户卡片
 *
 * @author Kaiju Zhao
 * @version V1.0.0
 * @date 2016-05-09
 */
public class ManageUserCardAction extends BaseAction<AdditionalUserCardModel> implements ModelDriven<AdditionalUserCardModel> {

    @Resource
    private AdditionalUserCardService userCardService;

    @Resource
    private CardRuleService cardRuleService;

    private AdditionalUserCardModel model = new AdditionalUserCardModel();

    public AdditionalUserCardModel getModel() {
        return model;
    }

    private Map<String, Object> data;

    /**
     * 进入用户卡片管理页面
     *
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/userCard/userCardManager")
    public String userCardManager() {
        return "userCardManager";
    }

    /**
     * 获取所有用户卡片列表
     *
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/userCard/userCardList")
    public void userCardList() throws IOException {
        // 初始化status值为99，表示查询所有
        String status = paramString("status");
        if (StringUtil.isBlank(status)) {
            model.setStatus(UserCardStatus.STATUS_UNKNOWN);
        }

        data = new HashMap<String, Object>();
        PageDataList<AdditionalUserCardModel> pageDataList = userCardService.list(model);
        data.put("total", pageDataList.getPage().getTotal());
        data.put("rows", pageDataList.getList());
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 导出用户卡片报表
     *
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/userCard/exportUserCardToExcel")
    public void exportUserCardToExcel() throws Exception {
        response.setContentType("application/msexcel;charset=UTF-8");

        int page  = model.getPage();
        int rows = model.getRows();
        if (0 == page) {
            model.setPage(1); // 默认第一页
        }
        if (0 == rows) {
            model.setRows(5000); // 默认导出5000条记录
        }

        // 获取记录
        PageDataList<AdditionalUserCardModel> pageDataList = userCardService.list(model);

        String title = "用户卡片获取记录Excel表";
        String[] hearders = new String[] { "编号", "用户名", "卡片名称", "卡片类型", "状态", "有效天数","过期时间","使用时间","获取时间", "卡片来源", "使用类型" };// 表头数组
        String[] fields = new String[] { "id", "userName", "name", "typeStr", "statusStr", "validDay", "expiredTime","useTime","addTime","sourceType","useTypeStr"};// 对象属性数组
        TableData td = ExcelUtils.createTableData(pageDataList.getList(), ExcelUtils.createTableHeader(hearders), fields);
        JsGridReportBase report = new JsGridReportBase(request, response);
        report.exportToExcel(title, getOperator().getUserName(), td);
    }

    /**
     * 置用户卡片为无效
     *
     * @throws Exception
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/userCard/updateUserCardInvalid")
    public void updateUserCardInvalid() throws Exception {
        Operator operator = getOperator();
        if (null == operator) {
            printResult("请先登录！", false);
            return;
        }
        int result = userCardService.updateUserCardInvalid(model.getId());
        if (result > 0) {
            printWebSuccess();
            printResult(MessageUtil.getMessage("MS101002001"), true);
        } else {
            printWebResult("将用户卡片标记为无效失败，请确认用户卡片是否已是未使用状态！", false);
        }
    }

    /**
     * 发放用户卡片页面
     *
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/userCard/append")
    public String append() {
        List<CardRuleModel> usableCardRuleList = cardRuleService.findUsableCardRules();
        request.setAttribute("usableCardRuleList", usableCardRuleList);
        return "append";
    }

    /**
     * 发放用户卡片
     *
     * @author Kaiju Zhao
     */
    @Action("/modules/additional/card/userCard/doAppend")
    public void doAppend() throws Exception{
        data = new HashMap<String, Object>();
        User user = UserUtils.getUserByUserName(model.getUserName());
        if (null == user) {
            printWebResult("该用户不存在！", false);
            return;
        }
        checkUserCardModel(model);

        CardRule cardRule = cardRuleService.findCardRuleById(model.getCardRuleId());
        if (null == cardRule) {
            printWebResult("该卡片规则不存在！", false);
            return;
        }

        userCardService.giveCard(user, cardRule.getType());
        data.put("result", "true");
        data.put("msg", MessageUtil.getMessage("MS101001001"));
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 校验用户卡片
     *
     * @param model
     * @author Kaiju Zhao
     */
    private void checkUserCardModel(AdditionalUserCardModel model) throws Exception {
        if (null == model) {
            throw new BusinessException("设置用户卡片模型为空!", BusinessException.TYPE_JSON);
        }

        int status = model.getStatus();
        if (UserCardStatus.STATUS_NO_USE != status
                && UserCardStatus.STATUS_USE != status
                && UserCardStatus.STATUS_EXPIRED != status
                && UserCardStatus.STATUS_INVALID != status) {
            throw new BusinessException("设置用户卡片状态不合法!", BusinessException.TYPE_JSON);
        }
    }

}